package com.example.zwgt.yrfk.ui.main;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.LatLng;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.PermissionCallback;
import com.blankj.utilcode.util.ToastUtils;
import com.example.zwgt.widget.NoScrollViewPager;
import com.example.zwgt.yrfk.R;
import com.example.zwgt.yrfk.base.mvpbase.BasePresenter;
import com.example.zwgt.yrfk.base.mvpbase.baseImpl.BaseActivity;
import com.example.zwgt.yrfk.ui.main.fragment.AccessFragment;
import com.example.zwgt.yrfk.ui.main.fragment.MyFragment;
import com.example.zwgt.yrfk.ui.main.fragment.RiskFragment;
import com.example.zwgt.yrfk.utils.PermissionsUtils;

import java.sql.Date;
import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity implements LocationSource, AMapLocationListener {

    @BindView(R.id.home_view_pager)
    NoScrollViewPager homeViewPager;
    @BindView(R.id.home_tab_layout)
    TabLayout homeTabLayout;
    @BindView(R.id.map)
    MapView mMapView;
    private static  final int PERMISSIONS_REQUEST_CAMERA=100001;
    //地图对象
    private AMap aMap;
    //声明AMapLocationClient类对象，定位发起端
    private AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象，定位参数
    public AMapLocationClientOption mLocationOption = null;
    //声明mListener对象，定位监听器
    private OnLocationChangedListener mListener = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private String[] mTitles = new String[]{"准入", "风控", "我的"};

    private int[] imgs = {R.mipmap.onenormal, R.mipmap.twonormal, R.mipmap.threenormal};
    String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_CALENDAR,
            Manifest.permission.BODY_SENSORS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_SMS, Manifest.permission.ACCESS_COARSE_LOCATION};


    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public BasePresenter initPresenter() {
        return null;
    }


    protected void initViews() {
        PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
        //Fragment页面加载
        homeViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                if (position == 1) {
                    return new RiskFragment();
                } else if (position == 2) {
                    return new MyFragment();
                }
                return new AccessFragment();
            }

            @Override
            public int getCount() {
                return mTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mTitles[position];
            }

        });
        //TabLayout绑定ViewPager
        homeTabLayout.setupWithViewPager(homeViewPager);
        //预加载全部
        homeViewPager.setOffscreenPageLimit(3);
        homeTabLayout.getTabAt(0).setCustomView(getTabView(0));
        homeTabLayout.getTabAt(1).setCustomView(getTabView(1));
        homeTabLayout.getTabAt(2).setCustomView(getTabView(2));

        homeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == homeTabLayout.getTabAt(0)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.onepress);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorAccent));
                    homeViewPager.setCurrentItem(0);
                } else if (tab == homeTabLayout.getTabAt(1)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.twopress);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorAccent));
                    homeViewPager.setCurrentItem(1);
                } else if (tab == homeTabLayout.getTabAt(2)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.threepress);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorAccent));
                    homeViewPager.setCurrentItem(2);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab == homeTabLayout.getTabAt(0)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.onenormal);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorGray));
                } else if (tab == homeTabLayout.getTabAt(1)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.twonormal);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorGray));
                } else if (tab == homeTabLayout.getTabAt(2)) {
                    ((ImageView) tab.getCustomView().findViewById(R.id.iv_icon)).setImageResource(R.mipmap.threenormal);
                    ((TextView) tab.getCustomView().findViewById(R.id.tv_title)).setTextColor(getResources().getColor(R.color.colorGray));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
        //创建监听权限的接口对象
        PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
            @Override
            public void passPermissons() {
                Toast.makeText(MainActivity.this, "权限通过，可以做其他事情!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void forbitPermissons() {
                Toast.makeText(MainActivity.this, "权限不通过!", Toast.LENGTH_SHORT).show();
            }
        };


    private View getTabView(int position) {

        View view = View.inflate(this, R.layout.tab_item, null);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        ImageView ivIcon = view.findViewById(R.id.iv_icon);

        tvTitle.setText(mTitles[position]);
        ivIcon.setImageResource(imgs[position]);

        if (position == 0) {
            tvTitle.setTextColor(getResources().getColor(R.color.colorAccent));
            ivIcon.setImageResource(R.mipmap.onepress);
        }

        return view;
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, 123);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
            //设置显示定位按钮 并且可以点击
            UiSettings settings = aMap.getUiSettings();
            aMap.setLocationSource(this);//设置了定位的监听
            // 是否显示定位按钮
            settings.setMyLocationButtonEnabled(true);
            aMap.setMyLocationEnabled(true);//显示定位层并且可以触发定位,默认是flase
        }
        location();
        ButterKnife.bind(this);
    }

    //开始定位
    private void location() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mLocationClient.stopLocation();//停止定位
        mLocationClient.onDestroy();//销毁定位客户端。
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    //实现LocationSource的方法
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //可在其中解析amapLocation获取相应内容。
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    //设置缩放级别
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                    //将地图移动到定位点
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //添加图钉
                    //  aMap.addMarker(getMarkerOptions(amapLocation));
                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(aMapLocation.getCountry() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getCity() + ""
                            + aMapLocation.getProvince() + ""
                            + aMapLocation.getDistrict() + ""
                            + aMapLocation.getStreet() + ""
                            + aMapLocation.getStreetNum());
                   ToastUtils.showShort(buffer.toString());
                    isFirstLoc = false;
                }
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }

    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //就多一个参数this
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
       location();
    }
}
